<?php
/**
 * Create by 11li
 * Date 2020/1/13
 * Time 15:15
 *
 */

namespace app\api\controller\v1;


use app\common\controller\Api;
use app\common\library\MyWeixin;
use app\common\service\OrderService;

class Notify extends Api
{
	protected $noNeedLogin = ['*'];
	
	public function weixinOrder() {
		$weixin = MyWeixin::getInstance();
		$data = $weixin->getNotifyDataToArray();
		if(!$data) {
			return '';
		}
		addApiLog('after', $data);
		
		
		
		$msg = '';
		$checkRes = $weixin->checkNofitySign($data);
		$orderRes = false;
		if($checkRes) {
			$arr = explode('_', $data['out_trade_no']);
			$orderId = $arr[0];
			$obj = new OrderService();
			$orderRes = $obj->paySuccess($orderId, $data['cash_fee']/100, $data['transaction_id']);
			if($orderRes) {
				$xml = "<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
</xml>";
				echo $xml;
			} else {
				$msg = '订单操作出错:'.$obj->getError();
			}
		} else {
			$msg = '签名不正确';
		}
		
		$log = [
			'checkRes' => $checkRes,
			'orderRes' => $orderRes,
			'msg' => $msg
		];
		
		addApiLog('after', $log);
		die;
	}
	
	public function wxRefund(){
		header('Content-type:text/html;charset=utf8');
		$weixin = MyWeixin::getInstance();
		$data = $weixin->getNotifyDataToArray();
		if(!$data) {
			return '';
		}
		addApiLog('after', $data);
		$msg = '';
		$checkRes = $weixin->checkNofitySign($data);
		$orderRes = false;
		if($checkRes) {
			$arr = explode('_', $data['out_trade_no']);
			$orderId = $arr[0];
			$orderType = $arr[1];
			$obj = new OrderService();
			$orderRes = $obj->refund($orderId, $orderType, $data['cash_fee']/100, $data['transaction_id']);
			if($orderRes) {
				$xml = "<xml>
 <return_code><![CDATA[SUCCESS]]></return_code>
 <return_msg><![CDATA[OK]]></return_msg>
</xml>";
				echo $xml;
			} else {
				$msg = '订单操作出错:'.$obj->getError();
			}
		} else {
			$msg = '签名不正确';
		}
		
		$log = [
			'checkRes' => $checkRes,
			'orderRes' => $orderRes,
			'msg' => $msg
		];
		
		addApiLog('after', $log);
		die;
	}
}